package com.leff.cards.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.leff.cards.R;
import com.leff.cards.data.AppState;
import com.leff.cards.data.Group;
import com.leff.cards.ui.fragment.GroupMembersFragment;
import com.leff.cards.ui.fragment.HistoryFragment;
import com.leff.cards.ui.fragment.QueryCardViewFragment;
import com.leff.cards.ui.util.FragmentTabListener;
import com.leff.cards.util.Dictionary;
import com.leff.cards.web.QueryDispatcher;
import com.leff.cards.web.requests.InviteRequest;
import com.leff.cards.web.requests.LeaveGroupRequest;
import com.leff.cards.web.requests.SelectCardRequest;
import com.leff.cards.web.requests.SubmitRequest;
import com.leff.notifications.NotificationCenter;
import com.leff.notifications.NotificationListener;

public class GroupActivity extends BaseActivity implements NotificationListener {
	
	private static final String SELECTED_TAB_KEY = "selected_tab";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		ActionBar actionBar = this.getSupportActionBar();
		
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	    actionBar.setDisplayShowTitleEnabled(true);
		
	    actionBar.addTab(
				actionBar.newTab()
				.setText(R.string.active_card)
				.setTabListener(new FragmentTabListener<QueryCardViewFragment>(this, "groups", QueryCardViewFragment.class))
				);
	    
	    actionBar.addTab(
				actionBar.newTab()
				.setText(R.string.history)
				.setTabListener(new FragmentTabListener<HistoryFragment>(this, "settings", HistoryFragment.class))
				);
	    
	    actionBar.addTab(
				actionBar.newTab()
				.setText(R.string.members)
				.setTabListener(new FragmentTabListener<GroupMembersFragment>(this, "group_members", GroupMembersFragment.class))
				);
	    
	    if(savedInstanceState != null) {
	    	int tab = savedInstanceState.getInt(SELECTED_TAB_KEY, 0);
	    	actionBar.setSelectedNavigationItem(tab);
	    }

	    NotificationCenter.registerListener(this, InviteRequest.INVITE_SUCCESSFUL);
	    NotificationCenter.registerListener(this, LeaveGroupRequest.GROUP_LEFT);
	    NotificationCenter.registerListener(this, SubmitRequest.CARDS_SUBMITTED);
	    NotificationCenter.registerListener(this, SelectCardRequest.CARDS_SELECTED);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
		int tab = this.getSupportActionBar().getSelectedNavigationIndex();
		outState.putInt(SELECTED_TAB_KEY, tab);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		NotificationCenter.unregisterListener(this, InviteRequest.INVITE_SUCCESSFUL);
		NotificationCenter.unregisterListener(this, LeaveGroupRequest.GROUP_LEFT);
		NotificationCenter.unregisterListener(this, SubmitRequest.CARDS_SUBMITTED);
		NotificationCenter.unregisterListener(this, SelectCardRequest.CARDS_SELECTED);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater MI = this.getSupportMenuInflater();
		MI.inflate(R.menu.group_menu, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.menu_leave_group) {
			
			showLeaveConfirmation();			
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onNotificationPosted(String action, Object data, Object sender) {
		super.onNotificationPosted(action, data, sender);
		
		if(action.equals(InviteRequest.INVITE_SUCCESSFUL)) {
			
			Dictionary dict = (Dictionary)data;
			
			long invited = (Long)dict.get("invited");
			long existed = (Long)dict.get("existed");
			
			String message = "";
			Resources res = this.getResources();
			if(existed > 0) {
				int resId = R.string.invite_result_both;
				message = String.format(res.getString(resId), invited, existed);
			}
			else {
				int resId = invited == 1 ? R.string.invite_result_invited_one : R.string.invite_result_invited;
				message = String.format(res.getString(resId), invited);
			}
			
			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
		}
		else if(action.equals(LeaveGroupRequest.GROUP_LEFT) || action.equals(SubmitRequest.CARDS_SUBMITTED)
				|| action.equals(SelectCardRequest.CARDS_SELECTED)) {
			
			String message = (String)data;
			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
			
			AppState.get().refreshGroups();
			
			this.finish();
		}
	}
	
	private void leaveGroup() {
		
		Group G = AppState.get().getActiveGroup();
		long userId = AppState.get().getUser().id;
		
		new QueryDispatcher(new LeaveGroupRequest(G.id, userId)).execute();
	}
	
	private void showLeaveConfirmation() {
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle(R.string.confirm_leave_title);
		builder.setMessage(R.string.confirm_leave_message);
		
		builder.setPositiveButton(R.string.leave_group, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				leaveGroup();
			}
		});
		builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		
		builder.create().show();
	}
}
